package server;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String,Context> contextMap;
    private String appBase;

    public RequestProcessor(Socket socket, Map<String, Context> contextMap,String appBase) {
        this.socket = socket;
        this.contextMap = contextMap;
        this.appBase = appBase;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            String projectName = "";
            String servletUrl = "";
            if(request.getUrl().indexOf("ico") < 0){

                 projectName = request.getUrl().split("/")[1];
                 servletUrl = "/"+request.getUrl().split("/")[2];

            }
            Context context = contextMap.get(projectName);
            Map<String,HttpServlet> servletMap = new HashMap<>();
            if(context == null){

                response.outputHtml(request.getUrl(),appBase);

            }else {

                servletMap = context.getServletMap();


                // 静态资源处理
                if(servletMap.get(servletUrl) == null) {
                    response.outputHtml(request.getUrl(),appBase);
                }else{
                    // 动态资源servlet请求

                    HttpServlet httpServlet = servletMap.get(servletUrl);
                    httpServlet.service(request,response);
                }
            }




            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
